<?php
namespace app\single\controller;
use think\Db;
class Order extends Common{
    /**
     * 获取子集VIP订单列表
     * @return [type] [description]
     */
    function index(){
        $uid=$this->user['id'];
        $map=[
            'pid'=>$uid,
            'type'=>1,
            'is_admin'=>0,
            'state'=>1,
            'money'=>['money','>',0]
        ];
        $options=[
            'order'=>'s_time desc,id',
            'field'=>'id,tel,s_time,expire_time,state,money,is_gain',
        ];
        $list=model($this->table)->readAll($map,0,$options);
        $time=time();
        foreach ($list as $k => $v) {
            if($v['expire_time']>0){
                $list[$k]['expire_day']=ceil(($v['expire_time']-$time)/86400);
            }else{
                $list[$k]['expire_day']=0;
            }
        }
        return json('',0,$list);
    }
    // 本月奖励排行榜
    function ranking(){
        $uid=$this->user['id'];
        $mine=[
            'rank'=>-1,
        ];
        $w=getWeek(-7*86400);
        $weekTime=$w[0];
        $weekEndTime=$w[1];

        $map=[
            // 'r.s_time'=>['r.s_time','between',[$weekTime,time()]],
        ];
        $field='r.uid,sum(r.money) as money,m.tel';
        $list=model('reward')->alias('r')->where($map)->join('member m','r.uid=m.id')->limit(10)->group('uid')->order('money desc')->field($field)->select()->toArray();
        $memberModel=model('member');
        foreach ($list as $k => $v) {
            $counts=$memberModel->where(['pid'=>$v['uid']])->count();
            if($v['uid']==$uid){
                $mine['rank']=$k+1;
                $mine['counts']=$counts;
                $mine['rank_money']=$v['money'];
            }
            $list[$k]['counts']=$counts;
        }
        
        if(!isset($mine['counts'])){
            $mine['counts']=$memberModel->where(['pid'=>$uid])->count('money');
        }
        if(!isset($mine['rank_money'])){
            $mine['rank_money']=model('reward')->alias('r')->where($map)->count('money');
        }
        return json('',0,[
            'list'=>$list,
            'mine'=>$mine,
            'week'=>[date('W')-1,date('m.d',$weekTime).'-'.date('m.d',$weekEndTime-1)],
        ]);
    }
    /**
     * 领取奖励
     * @param  integer $oid 订单ID
     * @return [type]       [description]
     */
    function gain($oid=0){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,vip_expire,vip_ratio');
        $time=time();
        if($user['vip_expire']<$time||$user['vip_ratio']<=0){
            return json('请您先开通会员，方可领取该奖励',1);
        }
        $map=[
            'id'=>$oid,
            'pid'=>$user['id'],
            'type'=>1,
            'is_admin'=>0,
        ];
        $has=model($this->table)->read($map,'id,uid,expire_time,state,money,is_gain');
        if(empty($has)){
            return json('该订单不存在,无法领取',1);
        }
        if(!$has['state']){
            return json('该订单未支付,无法领取',1);
        }
        if($has['is_gain']){
            return json('您已经领取过该订单的奖励了',1);
        }
        if($has['expire_time']!=0&&$has['expire_time']<$time){
            return json('未在有效期内开通会员，奖励已过期，无法领取',1);
        }
        $result=true;
        Db::startTrans();
        try {
            $money=$has['money']*$user['vip_ratio']/100;
            $data=[
                'uid'=>$user['id'],
                'from_id'=>$has['uid'],
                'order_id'=>$has['id'],
                'order_money'=>$has['money'],
                'ratio'=>$user['vip_ratio'],
                'money'=>$money,
                's_time'=>$time
            ];
            $log=model('reward')->add($data);
            if(empty($log)){
                exception('领取失败，请稍后再试');
            }
            $inc=model('member')->where(['id'=>$user['id']])->setInc('money',$money);
            if(!$inc){
                exception('领取失败，请稍后再试');
            }
            $edit=model($this->table)->edit(['id'=>$oid,'is_gain'=>1]);
            if(!$edit){
                exception('领取失败，请稍后再试');
            }
            $module=model('artmodule')->read(['name'=>'single'],'id');
            $f=model('finance')->log($user['id'],$has['uid'],$money,1,[
                'remark'=>'下级订单奖金领取',
                'order_id'=>$has['id'],
                'memo'=>'bonus_gain',
                'module_id'=>$module['id']
            ]);
            if(empty($f)){
                exception('系统繁忙,记录写入失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result=$e->getMessage();
        }
        if(true!==$result){
            return json($result,1);
        }
        
        $rs=[];
        $w=getWeek();
        $weekTime=$w[0];
        $weekEndTime=$w[1];
        // 本周收入
        $map=[
            'uid'=>$user['id'],
            's_time'=>['s_time','between',[$weekTime,$weekEndTime]],
        ];
        $rs['week_money']=model('reward')->where($map)->sum('money');
        $rs['bonus']=model('reward')->where(['uid'=>$user['id']])->sum('money');
        $money=model('member')->read(['id'=>$user['id']],'money');
        $rs['money']=$money['money'];
        return json('领取成功',0,$rs);
    }
    /**
     * 领取周奖励
     * @return [type] [description]
     */
    function weekGain(){
        $uid=$this->user['id'];
        // 本周
        $w=getWeek();
        $weekTime=$w[0];
        $weekEndTime=$w[1];

        $map=[
            'uid'=>$uid,
            'type'=>0,
            's_time'=>['s_time','between',[$weekTime,$weekEndTime]],
        ];
        $week_money=model('reward')->where($map)->sum('money');
        if($week_money<config('setting.week_standard')){
            return json('您本周奖励尚未达标不可领取',1);
        }
        $map['type']=1;
        $counts=model('reward')->where($map)->count();
        if($counts){
            return json('您已经领取过了本周的达标奖励,请下周再来',1);
        }
        $result=true;
        $time=time();
        Db::startTrans();
        try {
            $money=config('setting.week_bonus');
            $data=[
                'uid'=>$uid,
                'from_id'=>$uid,
                'order_money'=>$week_money,
                'money'=>$money,
                's_time'=>$time,
                'type'=>1,
            ];
            $log=model('reward')->add($data);
            if(empty($log)){
                exception('领取失败，请稍后再试');
            }
            $inc=model('member')->where(['id'=>$uid])->setInc('money',$money);
            if(!$inc){
                exception('领取失败，请稍后再试');
            }
            $module=model('artmodule')->read(['name'=>'single'],'id');
            $f=model('finance')->log($uid,$uid,$money,1,[
                'remark'=>'周达标奖金领取',
                'memo'=>'week_bonus_gain',
                'module_id'=>$module['id']
            ]);
            if(empty($f)){
                exception('系统繁忙,记录写入失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result=$e->getMessage();
        }
        if(true!==$result){
            return json($result,1);
        }
        $money=model('member')->read(['id'=>$uid],'money');

        $rs=[];
        $w=getWeek();
        $weekTime=$w[0];
        $weekEndTime=$w[1];
        // 本周收入
        $map=[
            'uid'=>$uid,
            's_time'=>['s_time','between',[$weekTime,$weekEndTime]],
        ];
        $rs['week_money']=model('reward')->where($map)->sum('money');
        $rs['bonus']=model('reward')->where(['uid'=>$uid])->sum('money');
        $money=model('member')->read(['id'=>$uid],'money');
        $rs['money']=$money['money'];
        return json('领取成功',0,$rs);
        
    }
}